#include <QMutexLocker>
#include <QDir>
#include <QTextStream>
#include <QApplication>
#include <QWidget>
#include <QSettings>
#include <QTextCodec>

#include <themes_manager/qls_themes_manager.h>
#include <settings/qls_settings.h>

/* 主题管理系统 */
QLsThemesManager::QLsThemesManager(QObject *parent) : QObject(parent)
{
    // 设置主题包内资源搜索路径
    QDir::setSearchPaths(
        "qss", QStringList()
                   << QString("%1/%2").arg(QLsSettings::getInstallPath(),
                                           QLS_PATH_THEMES)
                   << QString("%1/%2").arg(QLsSettings::getWorkSpace(),
                                           QLS_PATH_THEMES));
    QDir::setSearchPaths(
        "img", QStringList()
                   << QString("%1/%2/images")
                          .arg(QLsSettings::getInstallPath(), QLS_PATH_THEMES)
                   << QString("%1/%2/images")
                          .arg(QLsSettings::getWorkSpace(), QLS_PATH_THEMES));
    QDir::setSearchPaths(
        "icon", QStringList()
                    << QString("%1/%2/icons")
                           .arg(QLsSettings::getInstallPath(), QLS_PATH_THEMES)
                    << QString("%1/%2/icons")
                           .arg(QLsSettings::getWorkSpace(), QLS_PATH_THEMES));
    QDir::setSearchPaths(
        "svg", QStringList()
                   << QString("%1/%2/svg")
                          .arg(QLsSettings::getInstallPath(), QLS_PATH_THEMES)
                   << QString("%1/%2/svg")
                          .arg(QLsSettings::getWorkSpace(), QLS_PATH_THEMES));

    /* 初始化可用主题列表 */
    RefreshLocalThemes();
}

/* 更新本地主题 */
void QLsThemesManager::RefreshLocalThemes()
{
    /* 清空上次记录 */
    m_themesList.clear();

    // 打开本地主题包文件夹
    QStringList themes_filepath;
    // 工作路径
    QDir langPacksDir = QLsSettings::getWorkSpace();
    if (langPacksDir.cd(QLS_PATH_THEMES)) {
        themes_filepath << langPacksDir.entryList(QDir::Files);
    }
    // 安装路径
    if (QLsSettings::getWorkSpace() != QLsSettings::getInstallPath()) {
        langPacksDir = QLsSettings::getInstallPath();
        if (langPacksDir.cd(QLS_PATH_THEMES)) {
            themes_filepath << langPacksDir.entryList(QDir::Files);
        }
    }

    for (QString filename : themes_filepath) {
        /* 获取 *.qss 样式文件 */
        if (!filename.endsWith(".qss")) {
            continue;
        }

        /* 加入列表 */
        m_themesList.push_back(filename.chopped(strlen(".qss")));
    }
}

/* 加载主题 */
bool QLsThemesManager::LoadTheme(QWidget *widget, const QString &themeName)
{
    /* 判断当前主题是否存在 或 有无变化 */
    if (!m_themesList.contains(themeName) || m_curTheme == themeName)
        return false;

    /* 打开主题文件 */
    QFile file(QString("qss:%1.qss").arg(themeName));
    if (!file.open(QIODevice::ReadOnly))
        return false;

    /* 读取主题配置内容 */
    QTextStream in(&file);
    QString str = in.readAll();

    /* 加载主题：先清空上次样式表，否则会崩溃，qt的bug */
    //	widget->styleSheet().clear();
    widget->setStyleSheet(str);
    m_curTheme = themeName;

    /* 更新配置文件 */
    QSettings settings(QLS_FILEPATH_SETTINGS, QSettings::IniFormat);
    settings.setIniCodec(QTextCodec::codecForName("UTF-8"));
    settings.setValue(QLS_KEY_THEME, themeName);
    emit sigChangeTheme(themeName);

    return true;
}

/* 获取可用主题列表 */
QStringList QLsThemesManager::GetThemes() const
{
    return m_themesList;
}

/* 获取当前主题 */
QString QLsThemesManager::GetCurrentTheme() const
{
    return m_curTheme;
}
